/*
 * @Author: AskMeWhy
 * @Date:   2020-05-07 17:47:53
 * @Last Modified by: AskMeWhy
 * @Last Modified time: 2021-01-12 15:17:56
 */
import { handleMixins,basicMixins } from "./common";
import { AskComponent as _askComponent } from "./component";
import { merge } from "../utils/index";
import ApiServer from "../services/index";
import { staticUrl, serverUrl } from "../services/config.js";
import { resourcePathInfo } from "../common/resource.config.js";

const app = getApp();
const basicBehavior = {
    methods: {
        ...basicMixins,
        $_server(apiName, params) {
            return ApiServer.server[apiName](params);
        },
    },
};
const client = {
    id: "c2",
    secret: "secret",
};
let baseOption = {
    data: {
        _userId: "",
        $_resourcePathInfo: resourcePathInfo,
        $_config: {
            url: staticUrl || "",
            serverUrl: serverUrl,
            client,
        },
    },
};
export const basic = Behavior({
    ...baseOption,
    ...basicBehavior,
});
export const AskComponent = options=>{
    let askOption = {
        options: {
            styleIsolation: "shared",
        },
        behaviors: [basic],
    };

    options.behaviors = askOption.behaviors.concat(options.behaviors || []);
    askOption = merge(true, {}, askOption, options);
    if(!askOption.methods){
        askOption.methods = {};
    }
    askOption.methods.checkAuth = function () {
        const _page = this.getPage();
        let _auth = true;
        if(_page && _page.checkAuth){
            _auth = _page.checkAuth();
        }
        return _auth;
    };
    _askComponent(askOption);
};

const routerBefore = route => {
    let whiteList = [];
    if(whiteList.length === 0) return;
};

export const AskPage = options => {
    let askOption = {
        ...baseOption,
        ...basicBehavior.methods,
    };




    options = handleMixins(options);
    askOption = merge(true, {}, askOption, options);
    askOption.onShow = function (payLoad) {
        routerBefore(this.route);
        options.onShow && options.onShow.call(this, payLoad);
        
    };
    askOption.onLoad = function (payLoad) {

        var pages = getCurrentPages() //获取加载的页面

        var currentPage = pages[pages.length-1] //获取当前页面的对象

        var url = currentPage.route //当前页面url
        console.log("当前文件路径==========="+url)


        // 检测用户是否登录了不同的账户
        let _userInfo = app.user.userInfo;
        this.setData({
            _userId: _userInfo.id || "",
        });

        // if(app.user.token.length>0){
        //     //判断一下
        //     let openId = app.user.userInfo.openId;
        //     if(openId.length == 0){
        //         //绑定
                
        //         // wx.showModal({
        //         //     title: '提示',
        //         //     content: '小程序未绑定微信号，请前往绑定！',
        //         //     success: function(res) {
        //         //       if (res.confirm) {
        //         //           wx.navigateTo({
        //         //             url: '../personal/detail/index',
        //         //           })
        //         //         // console.log('用户点击确定')
        //         //       } else if (res.cancel) {
        //         //         // console.log('用户点击取消')
        //         //       }
        //         //     }
        //         //   })             
        //     }
        // }

      
        console.log("查看一下绑定微信没======",_userInfo);
                // wx.showModal({
                //     title: '提示',
                //     content: '小程序未绑定微信号，请前往绑定！',
                //     success: function(res) {
                //       if (res.confirm) {
                //           wx.navigateTo({
                //             url: '../personal/detail/index',
                //           })
                //         // console.log('用户点击确定')
                //       } else if (res.cancel) {
                //         // console.log('用户点击取消')
                //       }
                //     }
                //   })  

        wx.getNetworkType({
            success(res) {
                const networkType = res.networkType;
                if (networkType === "2g") {
                    wx.showToast({
                        title: "当前网络不好,不建议上传图片",
                        icon: "none",
                    });
                }
                if (networkType === "3g") {
                    wx.showToast({
                        title: "当前网络不好,建议单张图片上传",
                        icon: "none",
                    });
                }
            },
        });
        options.onLoad && options.onLoad.call(this, payLoad);
    };

    askOption.isCheckLogin=function(){


        let _userInfo = app.user;
        if (_userInfo.token) {
            return true;
        }
        // this.selectComponent("#pageBox").openAuth();
        return false;
    };
    //检测是否登录
    askOption.checkAuth = function () {
        let _userInfo = app.user;
        if (_userInfo.token) {
            return true;
        }
        // wx.navigateTo({
        //   url: '../pages/login/index',
        // })
        this.selectComponent("#pageBox").openAuth();
        return false;
        // return true;
    };
    // 检测是否更改了登录账户
    // 检测用户是否登录了不同的账户
    askOption.checkUserChange = function () {
        let _userInfo = app.user;
        if (!_userInfo.token) {
            return false;
        }
        if (_userInfo.userInfo.id === this.data._userId) {
            return false;
        }
        this.setData({
            _userId: _userInfo.id || "",
        });
        return true;
        // return true;
    };
    //这里的都是为了处理以前的老数据而写的
    askOption.formatTextToArray = function (value, sep = ",") {
        if (!value) return [];
        let isArray = Array.isArray(value);
        if (isArray) return value;
        if (typeof value === "string") {
            const reg = new RegExp(sep + "s+", "g");
            const _v = value.replace(reg, sep).replace(/\[|\]|^\s+/g, "");
            return _v ? _v.split(sep) : [];
        }
        return [];
    };
    askOption.removeImageUrlHost = function (list) {
        if (!Array.isArray(list)) {
            return list ? list.replace(/^https?:\/\/(.*?)(:\d+)?\//, "/") : "";
        }
        let _list = list.map(cur => {
            return cur.replace(/^https?:\/\/(.*?)(:\d+)?\//, "/");
        });
        return _list;
    };
    askOption.addImageUrlHost = function (list) {
        if (!Array.isArray(list)) return list ? staticUrl + list.replace(/^\s/g, "") : "";
        let _list = list.map(cur => {
            return staticUrl + cur.replace(/^\s/g, "");
        });
        return _list;
    };
    askOption.switchUrl = function (url = null) {
        if (url) {
            wx.redirectTo({
                url,
            });
        } else {
            wx.navigateBack({
                delta: 1,
            });
        }
    };
    // askOption.bindWxAction = function(){
    //   console.log(app.user);
    // };
    askOption.bindWxAction=function (){

        let openId = app.user.userInfo.openId;
        let wxcode = app.user.wxcode;
        console.log(wxcode);
        if(openId.length==0){
          // if(wxcode.length==0){
           wx.login({
          timeout: 1110,
          success:res=>{
            // console.log(res)
            this.getOpenId(res.code);
          }
        }) 
        }else{
          this.bindWx(openId);
        }
    
    
      },
    askOption.getOpenId= async function(code){
       
     const response = await this.$_server("user/openId", {
      data: {code: code},});
      let { data } = response;
      console.log(data);
      if (data.code !== 200) {
          wx.showToast({
            title: data.message,
            icon: "none",
            duration: 2000,
          })
          return;
      }
      
      let openid = data.data;
      this.bindWx(openid);
      },
      askOption.bindWx= async function(openid){
        //   wx.showLoading({
        //     title: 'title',
        //   })
        const response = await this.$_server("user/bind", {
          data: {
            openId: openid,
          },
      });
      let { data } = response;
    
      if(data.code ==200){
        this.setData({
          openId:openid
        })
    
        app.user.userInfo.openId = openid;
        var userStorage = wx.getStorageSync("user");
        userStorage.userInfo.openId =openid;
        wx.setStorage({
          data: userStorage,
          key: 'user',
        })
    
      }
    
    
      wx.showToast({
        title: data.message,
        icon: "none",
        duration: 2000,
      })
    
    
      console.log(data);
    
      },
    


    /**
     * 将传入的Key值转换为对应的name值
     * @Author   陈龙
     * @DateTime 2018-08-28
     * @version  [version]
     * @param    {Object}   options
     * {
     *    type: '', //需要比较的值
     *    list: [], //需要比较的数据源,必须是数组
     *    key: 'value', //需要比较的值对应的key，默认为val
     *    name: 'name' //比较成功后返回对应key的值
     * }
     * @return   {[type]}   返回的传入name对应的值;
     */
    askOption.$key2Name = function (options, type = "key") {
        const key2Name = options => {
            let opt = { type: "", list: [], key: "value", name: "label" };
            opt = merge(true, opt, options);
            const { type, list, key: _key, name: _name } = opt;
            const res = [];
            const resObj = [];
            let _types = [];
            const typeIsArr = Array.isArray(type);
            if (!Array.isArray(list)) {
                return typeIsArr ? res : "";
            }
            _types = typeIsArr ? type : [type];
            _types.forEach(item => {
                const _index = list.findIndex(
                    // eslint-disable-next-line no-void
                    cur => cur[_key] !== void 0 && cur[_key] === item
                );
                if (_index !== -1) {
                    resObj.push(list[_index]);
                    res.push(list[_index][_name]);
                }
            });
            return {
                res: typeIsArr ? res : res[0] || "",
                resObj: typeIsArr ? resObj : resObj[0] || {},
            };
        };
        let res = key2Name(options);
        return type === "obj" ? res.resObj : res.res;
    };
    Page(askOption);
};
